package com.example.springboot.file.controller;

import com.example.springboot.file.constant.FileTypeEnum;
import com.example.springboot.file.entity.FileDatalVo;
import com.example.springboot.file.util.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件操作类
 */
@RestController
@RequestMapping(value = {"/fileUpload"})
public class FileUploadController {

    private static final Log log = LogFactory.getLog(FileUploadController.class);
//    @Autowired
//    private FileUploadService fileUploadService;

    /**
     * 异步文件上传，上传到tomcat服务本地目录
     *
     * @param file:上传文件
     * @param systemType：系统类型（1-基础业务子系统；2-指挥调度子系统；3-前端管理子系统；4-实战应用子系统；5-网吧子系统；6-系统运维子系统；7-其他）
     * @return String
     */
    @ResponseBody
    @RequestMapping(value = "/upload.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public FileDatalVo upload(@RequestParam("file") MultipartFile file, String systemType, HttpServletRequest request) {
        FileDatalVo fileDetailVo = new FileDatalVo();
        try {
            // 获取tomcat本地路径
            String basePath = request.getServletContext().getRealPath(File.separator);
            fileDetailVo = this.upload(file, systemType, basePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileDetailVo;
    }

    /**
     * 文件上传
     *
     * @param file
     * @param systemType：系统类型（1-基础业务子系统；2-指挥调度子系统；3-前端管理子系统；4-实战应用子系统；5-网吧子系统；6-系统运维子系统；7-其他）
     * @param basePath:路径
     * @return
     */
    private FileDatalVo upload(MultipartFile file, String systemType, String basePath) throws IOException {
        FileDatalVo fileDetailVo = new FileDatalVo();
        if (!file.isEmpty()) {
            // 文件真实路径：路径+文件名
            String subfix = FileUtil.getFileSubfix(file.getOriginalFilename());
            String fileName = System.currentTimeMillis() + subfix;

            //文件真实路径
            String filePath = basePath + FileTypeEnum.toEnum(systemType).getValue() + File.separator + fileName;
            File files = new File(filePath);
            files.delete();
            // 将内存图片写入到磁盘
            file.transferTo(new File(filePath));
//            FileUtils.writeByteArrayToFile(new File(filePath),file.getBytes());

            fileDetailVo.setFileType(subfix);
            fileDetailVo.setFilePath(filePath);
            fileDetailVo.setFileName(fileName);
            fileDetailVo.setMsg("上传成功");
            fileDetailVo.setStatus(true);
        }
        return fileDetailVo;
    }


    /**
     * 文件下载，根据文件路径下载到本地
     *
     * @return
     */
    @RequestMapping(value = {"/download"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public String download(String filePath, HttpServletRequest request, HttpServletResponse response) {

        InputStream in = null;
        OutputStream out = null;
        try {
            // 清空response
            response.reset();
            in = new FileInputStream(filePath);
            byte[] buf = FileUtils.readFileToByteArray(new File(filePath));

            // 设置response的Header
            String fileName = FileUtil.getFileRealName(filePath);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + buf.length);
            String contentType = FileUtil.getContentType(fileName);
            response.setContentType(contentType + ";charset=utf-8");
            out = response.getOutputStream();
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        return null;
    }
}
